import java.util.*;

/**
 * 406. 根据身高重建队列
 * https://leetcode-cn.com/problems/queue-reconstruction-by-height/
 */
public class Solutions_406 {
    public static void main(String[] args) {
        int[][] people = {{7, 0},  {4, 4},  {7, 1},  {5, 0},  {6, 1},  {5, 2}};
        // output: {{5, 0},  {7, 0},  {5, 2},  {6, 1},  {4, 4},  {7, 1}}

        int[][] result = reconstructQueue(people);
        System.out.println(Arrays.deepToString(result));
    }

    public static int[][] reconstructQueue(int[][] people) {
        // 排序规则
        Arrays.sort(people, new Comparator<int[]>() {
            @Override
            public int compare(int[] o1, int[] o2) {
                // 先按照 arr[0] 降序排列
                // 若 arr[0] 相同，则按照 arr[1] 升序排列
                return o1[0] != o2[0] ? o2[0] - o1[0] : o1[1] - o2[1];
            }
        });
        List<int[]> list = new LinkedList<>();
        for (int[] arr : people) {
            // 关键：插入到 arr[1] 索引上，后面的元素后移
            list.add(arr[1], arr);
        }
        // 转成二维数组
        int[][] res = list.toArray(new int[people.length][2]);
        return res;
    }
}
